
package com.project.lk.nurseapp.thermomter;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.base.UrlContants;
import com.project.lk.nurseapp.common.adapter.TypeItemAdapter;
import com.project.lk.nurseapp.common.bean.TypeItemBean;
import com.project.lk.nurseapp.common.view.PercentView;
import com.project.lk.nurseapp.common.view.bluetooth.BleManager;
import com.project.lk.nurseapp.common.view.bluetooth.BluetoothListActivity;
import com.project.lk.nurseapp.inputfiles.InputThermomterActivity;
import com.project.lk.nurseapp.thermomter.presenter.IPostTemView;
import com.project.lk.nurseapp.thermomter.presenter.PostTemPresenter;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.ByteToStringUtils;
import com.project.lk.nurseapp.utils.PopWindowManager;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.TimeUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.TypeUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * 功能介绍：蓝牙模块方法调用基本一样，返回数据根据不同的设备返回不同的16进制进行数据分析，体温计测量界面
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class ThermomterActivity extends BaseActivity implements IPostTemView{


    @BindView(R.id.hint_tv)
    TextView hintTv;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.thermometer_num_tv)
    TextView thermometerNumTv;
    @BindView(R.id.type_recyclerview)
    RecyclerView typeRecyclerview;
    @BindView(R.id.record_recyclerview)
    RecyclerView recordRecyclerview;
    @BindView(R.id.thermometer_chart)
    LineChart thermometerChart;
    @BindView(R.id.percentView)
    PercentView percentView;
    private PopupWindow bluePopupWindow;
    private View blueContentView;
    private View praentView;
    private BleManager bleManager;
    private TypeItemAdapter typeAdapter;
    private List<TypeItemBean> typeItemBeanList;
    private String login="";
    private PostTemPresenter presenter;

    @Override
    protected void initData() {
        login = getIntent().getStringExtra("login");
        if (TextUtils.equals(login,"login")) {
            presenter = new PostTemPresenter(this);
        }
        setBluetoothPopwind();
        percentView.setAngel(60);
//        percentView.setRankText("","100");
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void initView() {
        bleManager = BleManager.init();
        bleManager.initialize();
        typeItemBeanList = new ArrayList<>();
        for (int i = 0; i < typeStr.length; i++) {
            TypeItemBean typeItemBean = new TypeItemBean();
            typeItemBean.setColor(typeColor[i]);
            typeItemBean.setSelect(false);
            typeItemBean.setTitle(typeStr[i]);
            typeItemBeanList.add(typeItemBean);
        }
        typeAdapter = new TypeItemAdapter(typeItemBeanList, this);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(typeStr.length, StaggeredGridLayoutManager.VERTICAL);
        typeRecyclerview.setAdapter(typeAdapter);
        typeRecyclerview.setLayoutManager(manager);
        YData.clear();
        YData.add(Float.valueOf(0));
        setLineChart(false); //设置默认数据


    }
    int[] typeColor = new int[]{
            R.color.blue, R.color.little_green,
            R.color.orange,
            R.color.red};
    String[] typeStr = new String[]{"低温", "正常", "低烧", "高烧"};

    @Override
    protected int getLayoutId() {
        return R.layout.activity_thermomter;
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleManager.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleManager.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    StringBuilder builder1 = new StringBuilder();
    /*广播回调*/
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BleManager.ACTION_GATT_CONNECTED.equals(action)) {
                Log.e("MLOG", "ACTION_GATT_CONNECTED");
//                hintTv.setText("已连接");
            } else if (BleManager.ACTION_GATT_DISCONNECTED.equals(action)) { //蓝牙断开连接
                Log.e("MLOG", "ACTION_GATT_DISCONNECTED");
                SharedPreferencesUtils.setParam("Thermom", false);
                hintTv.setText("未连接");
            } else if (BleManager.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {  //蓝牙连接成功
                // Show all the supported services and characteristics on the user interface.
                List<BluetoothGattService> supportedGattServices = bleManager.getSupportedGattServices();
                showList(supportedGattServices);
                infoBluetooth();
                bleManager.initNotify();
            } else if (BleManager.ACTION_DATA_AVAILABLE.equals(action)) {  //蓝牙数据返回
                if (intent.getStringExtra(BleManager.EXTRA_DATA) != null) {
                    String codeThermom = intent.getStringExtra(BleManager.EXTRA_DATA);
                    Log.e("MLOG", intent.getStringExtra(BleManager.EXTRA_DATA));
                    String[] splitThermom = null;
                    //AF 6A 72 5A 0E 46 00 00
                    String thermom = null;
                    if (codeThermom != null) {
                        splitThermom = codeThermom.toString().split(" ");
                        if (codeThermom.toString().split(" ").length == 8) {  //正常获取
                            thermom = splitThermom[4] + splitThermom[5];
                        } else if (codeThermom.toString().split(" ").length == 7) { //只返回数据7对
                            if (TextUtils.equals(splitThermom[2], "5A")) {
                                thermom = splitThermom[3] + splitThermom[4];
                            } else {
                                thermom = splitThermom[4] + splitThermom[5];
                            }
                        } else if (codeThermom.toString().split(" ").length == 6) {  //只返回数据6对
                            if (TextUtils.equals(splitThermom[0], "AF")) {
                                thermom = splitThermom[4] + splitThermom[5];
                            } else if (TextUtils.equals(splitThermom[0], "6A")) {
                                thermom = splitThermom[3] + splitThermom[4];
                            } else {
                                thermom = splitThermom[2] + splitThermom[3];
                            }
                        } else {                                           //数据分段处理
                            builder1.append(codeThermom);
                            if (builder1.length() > 15) {
                                Log.e("MLOG", builder1.toString() + ">>>>>" + builder1.length());
                                splitThermom = builder1.toString().split(" ");
                                for (int i = 0; i < splitThermom.length; i++) {
                                    if (TextUtils.equals(splitThermom[i], "72") && TextUtils.equals(splitThermom[i + 1], "5A")) {
                                        if (splitThermom.length >= i + 3) {
                                            thermom = splitThermom[i + 2] + splitThermom[i + 3];
                                        } else {
                                            builder1.delete(0, builder1.length()); //测量失败了，就删除当前需要累增的数据
                                            ToastUtils.showShortToast("测量错误，请重新测量");
                                        }

                                    }
                                }

                            }
                        }
                        if (thermom != null) {
                            if (!thermom.contains("0000")) {
                                String thermomterStr = ByteToStringUtils.hexThermomterStr(thermom);
                                thermometerNumTv.setText(thermomterStr);
                                timeTv.setText(TimeUtils.getSateTime(new Date()));
                                int thermomterType = TypeUtils.getThermomterType(thermomterStr);
                                for (int i = 0; i < typeItemBeanList.size(); i++) {
                                    typeItemBeanList.get(i).setSelect(false);
                                }
                                typeItemBeanList.get(thermomterType).setSelect(true);
                                typeAdapter.setTypeList(typeItemBeanList);
                                typeAdapter.notifyDataSetChanged();
                                YData.add(Float.parseFloat(thermomterStr));
                                setLineChart(true);
                            }
                            builder1.delete(0, builder1.length()); //测量有结果了，就删除当前需要累增的数据
                            //TODO:上传数据到服务器。。。
//                            if (presenter!=null) {
//                                presenter.postTemDate(new UserInfoUtils().getHealthUrl()+UrlContants.POST_TEM_URL,
//                                        thermomterStr,TypeUtils.getThermomterStr(thermomterStr), TimeUtils.getSateTime(new Date()));
//                            }
                        }
                    }


                }

            }
        }
    };

    /*获取蓝牙服务列表*/
    List<BluetoothGattCharacteristic> mBluetoothList=new ArrayList<>();
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void showList(List<BluetoothGattService> gattServices){
        for (BluetoothGattService gattService : gattServices) {
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                mBluetoothList.add(gattCharacteristic);
            }
        }
    }
    /*设置蓝牙服务可读可写*/
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void infoBluetooth(){
        for (BluetoothGattCharacteristic characteristic : mBluetoothList){
            bleManager.setCharacteristicNotification(
                    characteristic, false);
        }

    }
    @Override
    protected void onResume() {
        super.onResume();
        Boolean isConn = (Boolean) SharedPreferencesUtils.getParam("Thermom", false);//通过share保存蓝牙连接状态
        if (isConn) {
            hintTv.setText("已连接");
        }else {
            hintTv.setText("未连接");
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

    }


    List<Float> YData=new ArrayList<>();
    private void setLineChart(boolean isDefault) {
        if (isDefault) {
            if (YData.get(0)==0) {
                YData.remove(0);
            }
        }
        List<Entry> entries = new ArrayList<Entry>();
            for (int i=0;i<YData.size();i++){
                entries.add(new Entry(i,YData.get(i)));
            }
        Description description = new Description();
        description.setText("最近测量体温");//描述文字
        //description.setPosition(50f,50f);//文字位置，默认图表右下角
        description.setTextColor(Color.RED);//描述文字字体颜色
        LineDataSet dataSet = new LineDataSet(entries, "体温计"); // add entries to dataset
        dataSet.setColor(Color.RED);
        dataSet.setCircleColor(Color.RED);
        dataSet.setDrawValues(false);
        LineData lineData = new LineData(dataSet);
        thermometerChart.setDescription(description);
        thermometerChart.setData(lineData);
        thermometerChart.invalidate(); // refresh
        //获取右边的轴线
        YAxis rightAxis=thermometerChart.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        XAxis xAxis = thermometerChart.getXAxis();
        xAxis.setEnabled(true);//设置轴启用或禁用 如果禁用以下的设置全部不生效
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
            // turn your data into Entry objects

//        thermometerChart.setData(lineData);
    }

    @OnClick({R.id.back, R.id.start_test_but, R.id.record_tv,R.id.hint_tv,R.id.conn_device_but,R.id.input_but})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.start_test_but: //开始测试

                break;
            case R.id.record_tv://历史记录
                    startActivity(new Intent(this,ThermomterHistoryActivity.class));
                break;
            case R.id.hint_tv://
                if (hintTv.getText().equals("未连接")){

                    PopWindowManager.showAsLocationWindow(praentView,blueContentView,bluePopupWindow,R.id.bluetooth_popwind_layout);
                }
                break;
            case R.id.conn_device_but://连接设备
                if (hintTv.getText().equals("未连接")){

                    PopWindowManager.showAsLocationWindow(praentView,blueContentView,bluePopupWindow,R.id.bluetooth_popwind_layout);
                }
                break;
            case R.id.input_but://手动输入档案
                    startActivity(new Intent(this, InputThermomterActivity.class));
                break;
        }
    }

    //设置弹窗
    private void setBluetoothPopwind() {
        praentView = LayoutInflater.from(this).inflate(R.layout.activity_msg_list, null);
        blueContentView = LayoutInflater.from(this).inflate(R.layout.bluetooth_popwind_layout, null);
        bluePopupWindow = new PopupWindow(blueContentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        Button cancelBut = (Button) blueContentView.findViewById(R.id.cancel_but);
        Button commentBut = (Button) blueContentView.findViewById(R.id.setting_but);

        //点击事件
        setEvent(cancelBut, commentBut, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.cancel_but: //取消
                        bluePopupWindow.dismiss();
                        break;
                    case R.id.setting_but:  //设置
                        bluePopupWindow.dismiss();
                    startActivity(new Intent(ThermomterActivity.this, BluetoothListActivity.class));
                        break;
                }

            }
        });
    }

    //设置点击事件
    private void setEvent(Button cancelBut, Button commentBut, View.OnClickListener listener) {
        cancelBut.setOnClickListener(listener);
        commentBut.setOnClickListener(listener);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bleManager!=null) {
            bleManager.disableBlueBle("Thermom");
        }
        if (mGattUpdateReceiver!=null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
        if (presenter!=null) {
            presenter.dettachView();
            presenter=null;
        }
    }

    @Override
    public void postSuccess() {

    }

    @Override
    public void postFail() {

    }
}
